import React, { Component } from 'react';
import { observer, inject } from "mobx-react";
import QueueAnim from 'rc-queue-anim';
import _ from 'lodash'
import cass from 'classnames';
import { Card, Modal, Button, Icon, Popover, Dropdown, Menu, Popconfirm, message } from 'antd';
import s from './process.module.less';
import config from '../../config';

const { baseUrl } = config;

@inject(({ chatState, commonState, projectState }) => ({ chatState, commonState, projectState }))
@observer
class ProcessContent extends Component {

    state = {
        unOpen: true,
        visible: false,
        isAllComplete: false
    }

    viewStage = ({ stageid }, isOption) => {
        const { viewStage } = this.props.chatState;
        this.setState({ unOpen: true });
        viewStage(stageid, isOption);
    }

    selectTopic = (t, i) => {
        if (!this.isLawyer) { // 不是律师组成员不可以操作
            return;
        }
        const { selectTopic, mustStages, activeStageIndex, currentStage, nextStage } = this.props.chatState;
        if (t.stageid !== mustStages[activeStageIndex].stageid && mustStages.some(v => v.stageid === t.stageid)) {
            message.warn('请切换至启动流程');
            return
        };
        selectTopic(t, i, topics => {
            // 全部都完成了自动跳下一个流程
            if (mustStages[activeStageIndex + 1] && topics && topics.every(t => t.ischecked)) {
                const currentstageid = mustStages[activeStageIndex].stageid;
                const nextstageid = mustStages[activeStageIndex + 1].stageid;
                nextStage({
                    groupid: currentStage.groupid, currentstageid, nextstageid, topics,
                    nextstageIndex: activeStageIndex + 1
                }, (success) => {
                    if (success) message.success('推进成功');
                    else message.error('操作失败');
                });
            }
        });
    }

    goBack = (isBack, isCan) => {
        if (!isCan) return;
        const { currentStage } = this.props.chatState;
        // 返回的时候检查当前全部未完成，前进的时候检查全部完成
        const isAllComplete = currentStage.topics.every(v => v.complete === !isBack);
        this.setState({ visible: true, isBack, isAllComplete });
    }

    onSure = (all) => {
        const { mustStages, currentStage, activeStageIndex, nextStage } = this.props.chatState;
        const { isBack, isAllComplete } = this.state;

        const currentstageid = mustStages[activeStageIndex].stageid;
        const nextstageid = mustStages[isBack ? activeStageIndex - 1 : activeStageIndex + 1].stageid;
        let topics = currentStage.topics.concat().map(v => ({ topicid: v.topicid, ischecked: v.complete }));
        if (all && !isAllComplete) { // 是全部更改 有未完成
            topics = topics.concat().map(v => ({ ...v, ischecked: !isBack }));
        }

        nextStage({
            groupid: currentStage.groupid, currentstageid, nextstageid, topics,
            nextstageIndex: isBack ? activeStageIndex - 1 : activeStageIndex + 1
        }, (success) => {
            if (success) message.success(isBack ? '返回成功' : '推进成功');
            else message.error('操作失败');
            this.setState({ visible: false, isAllComplete: false });
        });
    }

    optionClick = (v, i) => {
        const { handleOptionStage } = this.props.chatState;
        handleOptionStage(!v.checked, i);
    }

    renderMenu(content) {
        return (
            <Menu onClick={({ domEvent, key }) => this[key](domEvent, content)}>
                <Menu.Item key="onOpenCreateTaskModal">新建任务</Menu.Item>
            </Menu>
        );
    }

    onOpenCreateTaskModal = (domEvent, content) => {
        domEvent.stopPropagation();
        domEvent.preventDefault();
        const { commonState: { onCreateTaskModalChange } } = this.props;
        onCreateTaskModalChange({
            taskModal: true,
            baseData: { content }
        });
    }

    onTopicTextClick = (e, t) => {
        if (t.value && t.value.url) {
            e.stopPropagation();
            e.preventDefault();
            const ext = t.value.url.split('.')[1];
            const { ipcRenderer } = window.electron;
            ipcRenderer.send('download', { files: [{ filename: `${t.label}.${ext}`, url: `${baseUrl}/${t.value.url}` }] });
        }
    }

    renderTopicText = (item) => {
        const { topicname, config } = item;
        if (config) {
            const configArr = JSON.parse(config);
            // 遍历获取关键字数组
            const topicnameArr = configArr.reduce((pre, c) => {
                let newArr = pre.concat();
                pre.forEach((p, pi) => {
                    if (!p.value) {
                        const arr = [];
                        let lastText = p.label;
                        while (lastText && lastText.indexOf(c.text) > -1) {
                            const idx = lastText.indexOf(c.text);
                            const before = lastText.slice(0, idx);
                            if (before) arr.push({ label: before });
                            arr.push({ label: c.text, value: c });
                            lastText = lastText.slice(idx + c.text.length);
                        }
                        if (lastText) {
                            arr.push({ label: lastText });
                        }

                        if (arr.length) {
                            newArr = [
                                ...pre.slice(0, pi),
                                ...arr,
                                ...pre.slice(pi + 1)
                            ]
                        }
                    }
                });
                return newArr;
            }, [{ label: topicname }]);
            return topicnameArr.map((t, i) => (
                <span onClick={(e) => this.onTopicTextClick(e, t)} key={i} className={cass(s.topicText, { [s.topicKey]: !!t.value })}>{t.label}</span>
            ))
        }
        return topicname
    }

    render() {
        const { mustStages, optionalStages, currentStage, activeStageIndex, chatListCurrentItem } = this.props.chatState;
        const { detailData } = this.props.projectState;
        const { isBack, visible, isAllComplete } = this.state;
        if (!currentStage) return null;

        const text1 = isBack ? '当前流程中有部分工作已完成，是否将已完成的工作设为未完成并返回到上一流程？' : '当前流程中有部分工作未完成，是否将未完成的工作设为已完成并进入下一流程？';
        const text2 = isBack ? '是，将所有已完成的工作设为未完成并返回到上一流程' : '是，将所有未完成的工作设为已完成并进入下一流程';
        const text3 = `否，保留当前工作完成情况并${isBack ? '返回到上一流程' : '进入下一流程'}`;

        const canBack = activeStageIndex > 0;
        const canGo = activeStageIndex < (mustStages.length - 1);
        const isWeiXie = currentStage.groupname === '委托人协作团队';

        const content = (
            <div className={s.cont}>
                {optionalStages && optionalStages.length ? optionalStages.map((v, i) => (
                    <Popconfirm
                        key={v.stageid}
                        title={`确认${v.checked ? '结束' : '开启'}${v.stagename}流程`}
                        okText="确定"
                        cancelText="取消"
                        placement="bottomRight"
                        onConfirm={() => this.optionClick(v, i)}
                    >
                        <div className="hovergray">
                            {v.checked ? '结束' : '开启'}{v.stagename}流程
                        </div>
                    </Popconfirm>
                )) : '无可选阶段'}
            </div>
        );

        const checkedOptions = optionalStages.filter(v => v.checked);

        this.isBoss = _.get(detailData, 'islawyerhost') || _.get(detailData, 'islawyermanager');
        this.isLawyer = chatListCurrentItem && chatListCurrentItem.inlawyermember;

        if (!mustStages.length) {
            return null;
        }
        return (
            <div className={s.processContent}>
                {this.isBoss ? (
                    <Popover placement="bottomRight" content={content} trigger="click">
                        <span className={cass('mdi mdi-dots-horizontal', s.menu, 'mainColor')} />
                    </Popover>
                ) : null}
                <Card hoverable>
                    <div className={s.wrapStages}>
                        {this.isLawyer && !isWeiXie ? (
                            <Icon
                                type="arrow-left"
                                className={cass({ [s.disable]: !canBack })}
                                onClick={() => this.goBack(true, canBack)}
                            />
                        ) : null}
                        {mustStages.map(v => (
                            <div
                                key={v.stageid}
                                className={cass(s.stageItem, { [s.active]: v.checked })}
                                onClick={() => this.viewStage(v, false)}
                            >
                                {v.stagename}
                                {v.hasLine ? <div className={s.line} /> : null}
                            </div>
                        ))}
                        {this.isLawyer && !isWeiXie ? (
                            <Icon
                                type="arrow-right"
                                className={cass({ [s.disable]: !canGo })}
                                onClick={() => this.goBack(false, canGo)}
                            />
                        ) : null}

                    </div>
                    {checkedOptions.length ? (
                        <div className={cass(s.optionStages, { [s.optionalStages1]: !this.isLawyer })}>
                            <QueueAnim
                                type={['right', 'left']}
                                ease={['easeOutQuart', 'easeInOutQuart']}
                                component="div"
                            >
                                {optionalStages.filter(v => v.checked).map(v => (
                                    <div className={s.stageItem} key={v.stageid} onClick={() => this.viewStage(v, true)}>
                                        {v.stagename}
                                        {v.hasLine ? <div className={s.line} /> : null}
                                    </div>
                                ))}
                            </QueueAnim>
                        </div>
                    ) : null}
                    <div className={s.wrapStageDetail}>
                        <div
                            className={cass(s.stageDetail, {
                                [s.unOpen]: this.state.unOpen
                            })}
                        >
                            {_.get(currentStage, 'topics', []).map((t, i) => (
                                <div
                                    key={i}
                                    className={cass('hover', s.topic)}
                                    onClick={() => this.selectTopic(t, i)}
                                >
                                    {
                                        t.complete ?
                                            <span className="mdi mdi-checkbox-blank-circle" /> :
                                            <span className="mdi mdi-checkbox-blank-circle-outline" />
                                    }
                                    <Dropdown overlay={this.renderMenu(t.topicname)} trigger={['contextMenu']}>
                                        <div className={cass({ [s.complete]: t.complete })}>
                                            {this.renderTopicText(t)}
                                        </div>
                                    </Dropdown>
                                </div>
                            ))}
                        </div>
                        <div
                            className={cass(s.btn, {
                                [s.unOpen]: this.state.unOpen
                            })}
                            onClick={() => this.setState({ unOpen: !this.state.unOpen })}
                        >
                            <Icon type="double-left" />
                        </div>
                    </div>
                    <Modal
                        visible={visible}
                        closable={false}
                        footer={null}
                        width={400}
                        className={s.wrapModal}
                    >
                        <div className={s.tips}><span className="mdi mdi-alert-circle" />提示</div>
                        {isAllComplete && !isBack ? <div className={s.text}>当前流程的全部工作已经完成，是否推进到下一个流程？</div> : null}
                        {isAllComplete && isBack ? <div className={s.text}>是否回退到上一流程？</div> : null}
                        {!isAllComplete ? [
                            <div key={1} className={s.text}>{text1}</div>,
                            <div key={2} className={s.step}>{text2}</div>,
                            <div key={3} className={s.step}>{text3}</div>,
                            <div key={4} className={s.step}>取消，放弃操作</div>
                        ] : null}
                        <div className={s.wrapBtn}>
                            <Button onClick={() => this.setState({ visible: false })}>取消</Button>
                            {isAllComplete ? null : <Button onClick={() => this.onSure(false)}>否</Button>}
                            <Button onClick={() => this.onSure(true)} type="primary">是</Button>
                        </div>
                    </Modal>
                </Card>
            </div>
        );
    }
}

export default ProcessContent